import axios from 'axios'
import { useTokenStore } from '@/stores/token'
import {ElMessage} from "element-plus";

const request = axios.create({
  baseURL: '/api',
  timeout: 50000
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    const userStore = useTokenStore()
    const token = userStore.getToken()
    if (token) {
      config.headers.Authorization = userStore.getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    const { code, message } = response.data
    if (code === 200) {
      return response.data
    } else {
      ElMessage.error(message || '请求失败')
      return Promise.reject(new Error(message || '请求失败'))
    }
  },
  error => {
    ElMessage.error(error.message || '请求失败')
    return Promise.reject(error)
  }
)

export default request